package com.penghaisoft.microwms.product.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.wms.model.ProStorageSn;
import com.penghaisoft.microwms.common.dto.ProHandOutDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.product.dao.ProHandOutMapper;
import com.penghaisoft.microwms.product.dao.ProHandOutSnMapper;
import com.penghaisoft.microwms.product.dao.ProStorageSnMapper;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.ProHandOut;
import com.penghaisoft.microwms.common.data.model.ProHandOutSn;
import com.penghaisoft.microwms.product.service.IProHandOutService;

/**
 * <p>
 * 业务逻辑实现类
 * </p>
 * 
 * @author
 * @createDate 
 **/
@Service("proHandOutService")
public class ProHandOutServiceImpl extends BaseService implements IProHandOutService{
		@Autowired
		private ProHandOutMapper proHandOutMapper;
		
		@Autowired
		private ProStorageSnMapper proStorageSnMapper;
		
		@Autowired
		private ProHandOutSnMapper proHandOutSnMapper;
		
	  /**
	   * 新增记录
	   * @param baseResource
	   * @return
	   */
		@Override
		public Resp create(ProHandOut proHandOut){
			proHandOutMapper.create(proHandOut);
			return success();
		}

	  /**
	   * 删除记录（逻辑删除）
	   * @param baseResource
	   * @return
	   */
		@Override
		public Resp delete(ProHandOut proHandOut){
			proHandOutMapper.delete(proHandOut);
			return success();
		}
		
	  /**
	   * 查询列表
	   * @param pager
	   * @param baseResource
	   * @return
	   */
		@Override
		public Pager<ProHandOut> findListByCondition(int page, int rows,ProHandOut condition){
		    Pager<ProHandOut> pager = new Pager<>();
		    pager.setPage(page);
		    pager.setRows(rows);
    		condition.preQuery();
    		long size = proHandOutMapper.queryCount(condition);
    		List<ProHandOut> records = new ArrayList<ProHandOut> ();
    		if(size > 0){
    			records = proHandOutMapper.queryList(pager,condition);
    		}
			pager.setRecords(records);
			pager.setTotalCount(size);
			return pager;
		}

	  /**
	   * 查询单条
	   * @param id
	   * @return
	   */
		@Override
		public ProHandOut findById(String id){
			return proHandOutMapper.queryById(id);
		}
		
	  /**
	   * 修改记录
	   * @param baseResource
	   * @return
	   */
		@Override
		public Resp update(ProHandOut proHandOut){
			proHandOutMapper.updateBySelect(proHandOut);
			return success();
		}

	@Override
	public Resp loadBill(ProHandOut proHandOut) {
		Resp resp = new Resp();

		proHandOut.setActiveFlag("1");
		List<ProHandOut> list = proHandOutMapper.queryByAny(proHandOut);

		if(list == null || list.isEmpty()){
			resp.setCode(Constant.FAIL);
			resp.setMsg("该手工出库单号不存在");
		}
		else {
			if(list.get(0).getHandOutStatus().equals("2")){
				resp.setCode(Constant.SUCCESS);
				resp.setMsg("该手工出库单已经发货完成！");
				return resp;
			}
			for(ProHandOut temp:list){
				if(temp.getHandOutStatus().equals("1") || temp.getHandOutStatus().equals("3")){
					resp.setCode(Constant.SUCCESS);
					resp.setMsg("提单成功！");
					return resp;
				}
			}
				
			resp.setCode(Constant.FAIL);
			resp.setMsg("该手工出库单审核！");
//			return resp;
		}
//		else{
//			Boolean flag_all_2 = true;
//			for(ProHandOut tmp : list){
////				0新建 1出库中 2出库完成
//				if("1".equals(tmp.getHandOutStatus()) || "3".equals(tmp.getHandOutStatus())){
//					flag_all_2 = false;
//				}
//			}
//			if(flag_all_2){
//				resp.setCode(Constant.FAIL);
//				resp.setMsg("该手工出库单已经发货完成！");
//				return resp;
//			}
//
//			resp.setCode(Constant.SUCCESS);
//			resp.setMsg("提单成功");
//		}
		return resp;
	}

	@Override
	public List<ProHandOut> queryListByAny(ProHandOut condition) {
		return proHandOutMapper.queryByAny(condition);
	}

	/* @Title: handOutScanBarcode 
	 * @Description: 出库扫码
	 * @author yanggm
	 * @date 2018年8月27日 上午9:58:32 
	 */
	@Override
	public TransResult handOutScanBarcode(ProHandOutDto proHandOutDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		if(isOutput(proHandOut)){
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单已经出库完成！");
			return result;
		}
		Date now = new Date();
		
		ProStorageSn proStorageSn = new ProStorageSn();
		proStorageSn.setBarcode(proHandOutDto.getBarcode());
		proStorageSn.setActiveFlag("1");
		//根据条码查找 仓库成品
		List<ProStorageSn> storageList = proStorageSnMapper.queryByAny(proStorageSn);
		if(storageList == null || storageList.isEmpty()){
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码不存在");
			return result;
		}else if(storageList.size()>1){
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码重复");
			return result;
		}else {
			ProStorageSn proStorageSnTemp = storageList.get(0);
//        	0：可用 1：冻结 2：已出库 
			if(proStorageSnTemp.getBarcodeStatus()==null){
				result.setCode(Constant.FAIL);
				result.setMsg("该成品条码状态为空");
				return result;
			}else if(proStorageSnTemp.getBarcodeStatus().equals("2")){
				result.setCode(Constant.FAIL);
				result.setMsg("该成品条码已出库");
				return result;
			}else if(proStorageSnTemp.getBarcodeStatus().equals("1")){
				result.setCode(Constant.FAIL);
				result.setMsg("该成品条码已冻结");
				return result;
			}else if(proStorageSnTemp.getBarcodeStatus().equals("0")){
				ProHandOutSn proHandOutSn = new ProHandOutSn();
				proHandOutSn.setBarcode(proHandOutDto.getBarcode());
				proHandOutSn.setActiveFlag("1");
				
				List<ProHandOutSn> handOutSnList = proHandOutSnMapper.queryByAny(proHandOutSn);
				if(!handOutSnList.isEmpty() && handOutSnList != null){
					result.setCode(Constant.FAIL);
					result.setMsg("该成品条码已扫描，不能再次扫描!");
					return result;
				}else {
//					ProHandOut proHandOut = new ProHandOut();
//					proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
					proHandOut.setModel(proStorageSnTemp.getModel());
					proHandOut.setGrade(proStorageSnTemp.getGrade());
					proHandOut.setLevel(proStorageSnTemp.getLevel());
					proHandOut.setType(proStorageSnTemp.getType());
					proHandOut.setActiveFlag("1");
					
					List<ProHandOut> handOutList = proHandOutMapper.queryByAny(proHandOut);
					if(handOutList.isEmpty() || handOutList == null){
						result.setCode(Constant.FAIL);
						result.setMsg("该条码不是出库单所需!");
						return result;
					}else {
						ProHandOut handOutTemp = handOutList.get(0);
						if("0".equals(handOutTemp.getHandOutStatus())){
							result.setCode(Constant.FAIL);
							result.setMsg("该条码不是当前出库单所需!");
							return result;
						}
						List<ProHandOut> rtnList = new ArrayList<>();
//						所需数量  实发数量  实发重量
						BigDecimal requireAmount = handOutTemp.getRequireAmount()==null?BigDecimal.ZERO:handOutTemp.getRequireAmount();
						BigDecimal realAmount = handOutTemp.getRealAmount()==null?BigDecimal.ZERO:handOutTemp.getRealAmount();
//						BigDecimal weight = handOutTemp.getWeight();//handOutTemp.getWeight()==null?BigDecimal.ZERO:
						if (realAmount.compareTo(requireAmount) == 0
								|| requireAmount.compareTo(realAmount) < 0) {
							result.setCode(Constant.FAIL);
							result.setMsg("该型号已经扫码完成，无需继续扫码!");
							return result;
						} else {
//							0新建 1出库中 2出库完成
							handOutTemp.setHandOutStatus("1");
							handOutTemp.setLastModifiedBy(proHandOutDto.getLoginName());
							handOutTemp.setGmtModified(now);
//							更新数量的sql 去掉realAmout和weight的更新
							handOutTemp.setRealAmount(null);
							handOutTemp.setWeight(null);
							
							handOutTemp.setRealAmountAdd(new BigDecimal(1));
							realAmount = realAmount.add(new BigDecimal(1));
							handOutTemp.setWeightAdd(proStorageSnTemp.getWeight());
						}
						Integer rtVal = proHandOutMapper.updateBySelect(handOutTemp);
						if(rtVal != 1){
							throw new RuntimeException("扫描条码失败，更新条数存在问题!");
						}
//						该实发数量、实发重量只是提供给手持显示，后台sql加
						handOutTemp.setRealAmount(realAmount);
						handOutTemp.setWeight(proStorageSnTemp.getWeight());
						
						//修改库存条码状态
						proStorageSnTemp.setBarcodeStatus("2");
						proStorageSnTemp.setLastModifiedBy(proHandOutDto.getLoginName());
						proStorageSnTemp.setGmtModified(now);
						
						int rtVal02 = proStorageSnMapper.updateByBarcodeStatus0(proStorageSnTemp);
						if(rtVal02!=1){
							throw new RuntimeException("该条码不在库中，或已被冻结！");
						}
						
//						返回给手持数据
						rtnList.add(handOutTemp);
						result.setList(rtnList);
						
						ProHandOutSn handOutSnInsertOb = new ProHandOutSn();
						handOutSnInsertOb.setHandOutNo(handOutTemp.getHandOutNo());
						handOutSnInsertOb.setBarcode(proHandOutDto.getBarcode());
						handOutSnInsertOb.setModel(handOutTemp.getModel());
						handOutSnInsertOb.setType(handOutTemp.getType());
						handOutSnInsertOb.setProductName(proStorageSnTemp.getProductName());
						handOutSnInsertOb.setDensity(proStorageSnTemp.getDensity());
						handOutSnInsertOb.setSpec(proStorageSnTemp.getSpec());
						handOutSnInsertOb.setWeight(proStorageSnTemp.getWeight());
						handOutSnInsertOb.setUnit(proStorageSnTemp.getUnit());
						handOutSnInsertOb.setMachineNumber(proStorageSnTemp.getMachineNumber());
						handOutSnInsertOb.setGrade(proStorageSnTemp.getGrade());
						handOutSnInsertOb.setLevel(proStorageSnTemp.getLevel());
						handOutSnInsertOb.setWlCode(proStorageSnTemp.getWlCode());
						handOutSnInsertOb.setActiveFlag("1");
						handOutSnInsertOb.setGmtCreate(now);
						handOutSnInsertOb.setCreateBy(proHandOutDto.getLoginName());

						proHandOutSnMapper.create(handOutSnInsertOb);
					}
				}
				
			}
		}
		
		return result;
	}

	/* @Title: handOutComplete 
	 * @Description: 出库完成，确认
	 * @author yanggm
	 * @date 2018年8月27日 上午10:27:24 
	 */
	@Override
	public TransResult handOutComplete(ProHandOutDto proHandOutDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		if(isOutput(proHandOut)){
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单已经出库完成！");
			return result;
		}
		Date now = new Date();
		
//		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setActiveFlag("1");
//		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		List<ProHandOut> handOutList = proHandOutMapper.queryByAny(proHandOut);
		if(handOutList == null || handOutList.isEmpty()){
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单不存在！");
			return result;
		}else{
			for(ProHandOut tmp: handOutList){
				BigDecimal requireAmount = tmp.getRequireAmount()==null?BigDecimal.ZERO:tmp.getRequireAmount();
				BigDecimal realAmount = tmp.getRealAmount()==null?BigDecimal.ZERO:tmp.getRealAmount();
				if(requireAmount.compareTo(realAmount) > 0){
					result.setCode(Constant.FAIL);
					result.setMsg("该出库单未扫码完毕！");
					return result;
				}else if(requireAmount.compareTo(realAmount) < 0){
					result.setCode(Constant.FAIL);
					result.setMsg("该出库单扫码数量超过需求数量!");
					return result;
				}
			}
			
			ProHandOutSn proHandOutSn = new ProHandOutSn();
			proHandOutSn.setHandOutNo(proHandOutDto.getHandOutNo());
			ProHandOutSn handOutSn = proHandOutSnMapper.selectBeginEndScanTime(proHandOutSn);
			
			ProHandOut handOutUpdateOb = new ProHandOut();
			handOutUpdateOb.setHandOutNo(proHandOutDto.getHandOutNo());
			handOutUpdateOb.setScanTimeBegin(handOutSn.getScanTimeBegin());
			handOutUpdateOb.setScanTimeEnd(handOutSn.getScanTimeEnd());
			handOutUpdateOb.setHandOutStatus("2");
			handOutUpdateOb.setLastModifiedBy(proHandOutDto.getLoginName());
			handOutUpdateOb.setGmtModified(now);
			proHandOutMapper.updateByHandOutNo(handOutUpdateOb);
			
		}
		
		return result;
	}

	/* @Title: handOutDelBarcode 
	 * @Description: 退扫
	 * @author yanggm
	 * @date 2018年8月27日 上午11:31:51 
	 */
	@Override
	public TransResult handOutDelBarcode(ProHandOutDto proHandOutDto) {
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		ProHandOut proHandOut = new ProHandOut();
		proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
		if(isOutput(proHandOut)){
			result.setCode(Constant.FAIL);
			result.setMsg("该手工出库单已经出库完成！");
			return result;
		}
		Date now = new Date();
		
		ProStorageSn proStorageSn = new ProStorageSn();
        proStorageSn.setBarcode(proHandOutDto.getBarcode());
//    	0：可用 1：冻结 2：已出库 3：抽检冻结
        proStorageSn.setBarcodeStatus("2");
        proStorageSn.setActiveFlag("1");
		List<ProStorageSn> storageSnList = proStorageSnMapper.queryByAny(proStorageSn);
		if(storageSnList==null || storageSnList.isEmpty()){
			result.setCode(Constant.FAIL);
			result.setMsg("该成品条码不存在或未出库");
			return result;
		}else if(storageSnList.size() > 1){
            result.setCode(Constant.FAIL);
            result.setMsg("该成品条码重复");
            return result;
        }else {
        	 ProStorageSn storageSnTemp = storageSnList.get(0);

        	 ProHandOutSn proHandOutSn = new ProHandOutSn();
        	 proHandOutSn.setHandOutNo(proHandOutDto.getHandOutNo());
        	 proHandOutSn.setBarcode(proHandOutDto.getBarcode());
        	 proHandOutSn.setActiveFlag("1");

             List<ProHandOutSn> handOutSnList = proHandOutSnMapper.queryByAny(proHandOutSn);
             if(handOutSnList == null || handOutSnList.isEmpty()){
                 result.setCode(Constant.FAIL);
                 result.setMsg("该条码未扫描!");
                 return result;
             }else {
            	 ProHandOutSn handOutSnTemp = handOutSnList.get(0);
            	 
//            	 ProHandOut proHandOut = new ProHandOut();
            	 proHandOut.setActiveFlag("1");
//            	 proHandOut.setHandOutNo(proHandOutDto.getHandOutNo());
            	 proHandOut.setModel(storageSnTemp.getModel());
            	 proHandOut.setGrade(storageSnTemp.getGrade());
            	 proHandOut.setLevel(storageSnTemp.getLevel());
            	 List<ProHandOut> handOutList = proHandOutMapper.queryByAny(proHandOut);
            	 if(handOutList==null || handOutList.isEmpty()){
            		 result.setCode(Constant.FAIL);
                     result.setMsg("条码型号与出库单所需型号、等级或级别不一致!");
                     return result;
            	 }else {
            		 ProHandOut handOutTemp = handOutList.get(0);
            		 List<ProHandOut> rtList = new ArrayList<>();
//            		 // 需求数量
//                     BigDecimal requireAmount = handOutTemp.getRequireAmount() ==null ? BigDecimal.ZERO : handOutTemp.getRequireAmount();
                     // 已发数量
                     BigDecimal realAmount = handOutTemp.getRealAmount() == null ? BigDecimal.ZERO : handOutTemp.getRealAmount();
//                     // 已发重量
//                     BigDecimal weight = handOutTemp.getWeight();//handOutTemp.getWeight()==null?BigDecimal.ZERO:
// 					0新建 1出库中 2出库完成
                     handOutTemp.setHandOutStatus("1");
                     handOutTemp.setLastModifiedBy(proHandOutDto.getLoginName());
                     handOutTemp.setGmtModified(now);
//                   更新时去掉realAmount和weight的更新
                     handOutTemp.setRealAmount(null);
                     handOutTemp.setWeight(null);
                     
                     handOutTemp.setRealAmountDel(new BigDecimal(1));
                     realAmount = realAmount.subtract(new BigDecimal(1));
                     handOutTemp.setWeightDel(storageSnTemp.getWeight());
//                     weight = weight.subtract(storageSnTemp.getWeight());

                     Integer rtVal = proHandOutMapper.updateBySelect(handOutTemp);
                     if(rtVal != 1){
                         throw new RuntimeException("删除条码失败，更新条数存在问题!");
                     }

// 					该实发数量、实发重量只是提供给手持显示，后台sql加
                     handOutTemp.setRealAmount(realAmount);
                     handOutTemp.setWeight(storageSnTemp.getWeight());
// 					返回给手持数据
                     rtList.add(handOutTemp);
                     result.setList(rtList);

                     handOutSnTemp.setActiveFlag("0");
                     handOutSnTemp.setLastModifiedBy(proHandOutDto.getLoginName());
                     handOutSnTemp.setGmtModified(now);

                     Integer rtVal1 = proHandOutSnMapper.updateBySelect(handOutSnTemp);
                     if(rtVal1 != 1){
                         throw new RuntimeException("退码失败，更新条数存在问题");
                     }

// 					0：可用 1：冻结 2：已出库 3：抽检冻结
                     storageSnTemp.setBarcodeStatus("0");
                     storageSnTemp.setLastModifiedBy(proHandOutDto.getLoginName());
                     storageSnTemp.setGmtModified(now);

                     Integer rtVal20 = proStorageSnMapper.updateByBarcodeStatus2(storageSnTemp);
                     if(rtVal20 != 1){
                         throw new RuntimeException("退码失败，更新条数存在问题!");
                     }
                     
            	 }
             }
             
		}
		
		return result;
	}

	/**
	 * 根据前段传过来的型号 数量 创建手工出库单
	 */
	@Override
	public Resp insert(List<ProHandOut> list, String handOutNo, String loginName) {
		Date date = new Date();
		HashSet<String> allSet = new HashSet<String>();
		for(int i = 0 ; i < list.size(); i ++){
			ProHandOut handOut = list.get(i);

			StringBuffer uniqueStr = new StringBuffer("");
			uniqueStr.append(handOut.getModel());
			uniqueStr.append(handOut.getGrade());
			uniqueStr.append(handOut.getLevel());
			if(allSet.contains(uniqueStr.toString())){
				Resp resp = new Resp();
				resp.setCode(Constant.FAIL);
				resp.setMsg("选择的型号、等级、级别重复");
				return resp;
			}else{
				allSet.add(uniqueStr.toString());
			}
		}
		for(int i=0;i<list.size();i++){
//			ProHandOut hand = new ProHandOut();
			ProHandOut hand = list.get(i);
			//写入 根据页面传来的值写入
			hand.setHandOutNo(handOutNo);
			
			hand.setActiveFlag("1");
			hand.setGmtCreate(date);
			hand.setCreateBy(loginName);
			hand.setHandOutStatus("0");
			hand.setRealAmount(new BigDecimal(0));
			
			proHandOutMapper.create(hand);
		}
		
		
		return success();
	}

	@Override
	public Resp updateByNo(ProHandOut proHandOut) {
		proHandOutMapper.updateByHandOutNo(proHandOut);
		return success();
	}

	@Override
	public List<ProHandOut> queryListByStatus(ProHandOut condition) {
		return proHandOutMapper.queryByStatus(condition);
	}
	
//	是否出库完成
	public boolean isOutput(ProHandOut proHandOut){
		proHandOut.setActiveFlag("1");
		List<ProHandOut> list = proHandOutMapper.queryByAny(proHandOut);
		if("2".equals(list.get(0).getHandOutStatus())){
			return true;
		}
		return false;
	}

}
